package com.cion.shardingjdbcDemo.services;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cion.shardingjdbcDemo.entity.Demo;
import com.cion.shardingjdbcDemo.repository.DemoRepository;
import com.cion.shardingjdbcDemo.utils.IdGenerator;

@Service
@Transactional
public class DemoService implements IDemoService{

	@Resource
	private DemoRepository demoRepository;
	
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	@Override
	@Transactional(readOnly=true)
	public void testFind(Demo demo) {

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withMatcher("id", GenericPropertyMatchers.exact());
        //创建实例
        Example<Demo> example = Example.of(demo, matcher); 
        
        Pageable pageable = PageRequest.of(0,3, Sort.Direction.DESC,"id");
        System.out.println("start jpa query.");
        Page<Demo> demopage = demoRepository.findAll(example, pageable);
        if(demopage.getTotalElements() > 0) {
        	for(Demo item : demopage.getContent()) {
            	System.out.println("find result: " + item.toString());
            }
        }else {
        	System.out.println("can not find any record.");
        }
        System.out.println("end jpa query.");
        System.out.println("start jdbcTemplate query.");
    	Object[] param = {demo.getId()};
    	List<Demo> list = jdbcTemplate.query("select * from test_table where id = ? ", param, new BeanPropertyRowMapper<Demo>(Demo.class));
    	if(!list.isEmpty()) {
    		for(Demo item : list) {
            	System.out.println("find result: " + item.toString());
            }
    	}else {
        	System.out.println("can not find any record.");
        }
    	System.out.println("end jdbcTemplate query.");
	}

	@Override
	public Demo testInsert() {
		Demo demo = new Demo();
		demo.setId(IdGenerator.getId());
		demo.setComment("inserttime=" + System.currentTimeMillis());
		demoRepository.save(demo);
		System.out.println("insert success: " + demo.getId());
		//同一线程会从主库查询
		testFind(demo);
		return demo;
	}
}
